<template>
  <div>
    <page-loading
      :loading.sync="pageLoading"
      :error.sync="pageError"
      :enable-pull-refresh="false"
      @reload="getRelatedBangumis"
    >
      <template v-if="hasInfo">
        <bangumi-player
          class="vp"
          :info="bangumiInfo"
        />

        <van-tabs
          ref="vanTabs"
          class="tabs"
          v-model="activeTab"
          :title-active-color="rootThemeColor"
          animated
          @change="onTabChange"
        >
          <van-tab title="简介">
            <bangumi-info
              :info="bangumiInfo"
              :fav-checked="favStatus"
              @fav-click="onFavClick"
            />
            <bangumi-episode
              :info="bangumiInfo"
              @select-episode="handleSelectEpisode"
              @select-season="handleSelectSeason"
            />
            <bangumi-part
              :info="bangumiInfo"
              @select-section="handleSelectEpisode"
            />
            <bangumi-related
              :bangumis="relatedBangumis"
            />
          </van-tab>
          <van-tab>
            <template #title>评论 <span v-if="totalCommentNum > 0">{{ totalCommentNum }}</span></template>
            <bangumi-comment
              :comments="comments"
              popup-class="bpopup"
            />
          </van-tab>
        </van-tabs>
      </template>
    </page-loading>
  </div>
</template>

<script>
import PageLoading from '@/components/page-loading/PageLoading.vue'
import BangumiPlayer from '@/components/bangumi/BangumiPlayer.vue'
import BangumiInfo from '@/components/bangumi/BangumiInfo.vue'
import BangumiEpisode from '@/components/bangumi/BangumiEpisode.vue'
import BangumiPart from '@/components/bangumi/BangumiPart.vue'
import BangumiRelated from '@/components/bangumi/BangumiRelated.vue'
import BangumiComment from '@/components/comment/Comment.vue'
import { Tabs as VanTabs, Tab as VanTab, Toast } from 'vant'
import { apiGetInfo, apiGetRelated, apiGetComment } from '@/api/bangumi.js'
import { getStorage, setStorage } from '@/utils/localStorage.js'
import pageLoadingMixin from '@/mixins/pageLoading.js'
export default {
  name: 'Bangumi',
  inject: ['rootThemeColor', 'rootTitle'],
  mixins: [pageLoadingMixin],
  metaInfo () {
    return {
      title: this.title
    }
  },
  components: {
    PageLoading,
    VanTabs,
    VanTab,
    BangumiPlayer,
    BangumiInfo,
    BangumiEpisode,
    BangumiPart,
    BangumiRelated,
    BangumiComment
  },
  props: {
    id: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      searchKey: this.id,
      bangumiInfo: null,
      videoPlayUrl: null,
      videoDuration: 0,
      relatedBangumis: [],
      comments: [],
      totalCommentNum: 0,
      activeTab: 0,
      seasonId: null,
      // episodeId: null,
      commentId: null,
      favStatus: false
    }
  },
  computed: {
    hasInfo () {
      return this.bangumiInfo !== null
    },
    title () {
      let word = this.rootTitle
      if (this.hasInfo) {
        word = `${this.bangumiInfo.mediaInfo.title}_番剧_${word}`
      }
      return word
    },
    description () {
      let word = this.rootDescription
      if (this.hasInfo) {
        word = (this.bangumiInfo.mediaInfo.evaluate || '').replace(/\n/g, '').substring(0, 200) || this.bangumiInfo.mediaInfo.title
      }
      return word
    }
  },
  watch: {
    id (newVal) {
      if (newVal) {
        this.searchKey = newVal
      }
    },
    searchKey (newVal) {
      this.pageError = false
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.getData()
    },
    seasonId (newVal) {
      if (newVal) {
        this.initFav()
        this.getRelatedBangumis()
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this.getData()
    },
    getData () {
      apiGetInfo({ id: this.searchKey }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { ssId, epInfo: { aid } } = data
          this.commentId = aid
          this.seasonId = ssId
          // this.episodeId = id
          this.bangumiInfo = data
        } else {
          this.pageError = true
        }
        return data
      }).catch(err => {
        console.log(err)
        this.pageError = true
      }).finally(() => {
        this.pageLoading = false
      })
    },
    // 获取和此番剧类似的其他番剧
    getRelatedBangumis () {
      apiGetRelated({
        id: this.seasonId
      }).then(res => {
        const { code, result } = res
        if (code === 0 && result) {
          const { season } = result
          this.relatedBangumis = season.slice(0, 6)
        }
      })
    },
    getComment () {
      apiGetComment({ oid: this.commentId }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          const { replies, page: { acount } } = data
          this.comments = replies
          this.totalCommentNum = acount
        }
      }).catch(err => {
        console.log(err)
      })
    },
    onTabChange (name) {
      if (name === 1 && !this.comments.length) {
        // 评论标签首次加载
        this.getComment()
      }
    },
    // 选择其他集数
    handleSelectEpisode (episode) {
      this.$router.push({ name: 'bangumi', params: { id: `ep${episode.id}` } })
    },
    // 选择其他剧
    handleSelectSeason (season) {
      this.$router.push({ name: 'bangumi', params: { id: `ss${season.season_id}` } })
    },
    initFav () {
      const favs = getStorage('bangumi_history')
      const matchIndex = favs.findIndex(fav => fav.seasonId === this.bangumiInfo.mediaInfo.season_id)
      this.favStatus = matchIndex > -1
    },
    onFavClick () {
      this.favStatus = !this.favStatus
      this.setHistory({
        type: 'bangumi_history',
        data: this.bangumiInfo,
        action: !this.favStatus ? 'del' : ''
      })
    },
    // 存储设置缓存
    setHistory ({ type, data, action = 'add' } = {}) {
      const vals = getStorage(type)
      const matchIndex = vals.findIndex(val => val.seasonId === data.mediaInfo.season_id)
      if (matchIndex === -1) {
        const { mediaInfo, mediaInfo: { title, cover } } = data
        const item = {
          seasonId: mediaInfo.season_id,
          title,
          cover,
          isHistory: 1,
          timestamp: new Date().getTime()
        }
        vals.unshift(item)
        setStorage(type, vals)
      } else {
        if (action === 'del') {
          vals.splice(matchIndex, 1)
          setStorage(type, vals)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  @media screen and (orientation:portrait) {
    // 竖屏
    .tabs ::v-deep .van-tabs__wrap {
      position: sticky;
      top: 255px;
      z-index: 2;
    }
    .vp{
      position: sticky;
      top: 44px;
      z-index: 2;
    }
  }
</style>
